package com.example.basic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.csvreader.CsvReader;
import com.example.basic.domain.SanctionsEntity;
import com.example.basic.service.CsvDownloadService;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mjw
 * @date 2023/3/23
 */
@Service
public class CsvDownloadServiceImpl implements CsvDownloadService {

    @Override
    public List<SanctionsEntity> csvSanctionDownload() {
        //获取文件请求路径（路径需要定义配置维护）
        String requestUrl = "https://www.treasury.gov/ofac/downloads/sdn.csv";
        List<SanctionsEntity> sanctionsEntityList = new ArrayList<>();
        try {
            //接口调用
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Resource> entity = restTemplate.exchange(requestUrl,
                    HttpMethod.GET, null, Resource.class);
            //获取文件流
            InputStream inputStream = entity.getBody().getInputStream();
            //文件解析
            CsvReader csvReader = new CsvReader(inputStream, StandardCharsets.UTF_8);

            Map<String, String> map = new HashMap<>(16);
            while (csvReader.readRecord()) {
                String[] fields = csvReader.getValues();
                if (fields.length > 1) {
                    map.put("entityNumber", fields[0]);
                    map.put("entityName", fields[1]);
                    map.put("sanctionsType", "SDN_LIST");
                    if ("-0-".equals(fields[2])) {
                        map.put("entityType", "other");
                    } else {
                        map.put("entityType", fields[2]);
                    }
                    map.put("mappingStatus", "PENDING");
                    SanctionsEntity sanctionsEntity = JSONObject.parseObject(JSONObject.toJSONString(map), SanctionsEntity.class);
                    sanctionsEntity.setSyncTime(new Date());
                    sanctionsEntityList.add(sanctionsEntity);
                } else {
                    System.out.println("识别失败：" + csvReader.getRawRecord());
                }
            }
            System.out.println(sanctionsEntityList.size());

            // 以entityName为key，自动去重

            sanctionsEntityList = sanctionsEntityList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SanctionsEntity::getEntityName))), ArrayList::new)
            );
            System.out.println(sanctionsEntityList.size());
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sanctionsEntityList;
    }
}
